package com.lvyuely.web.module.init;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.CronTriggerBean;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.lvyuely.web.module.entity.function.JobTimeExpression;
import com.lvyuely.web.module.job.BaseJob;

@Component
public class InitSystemConfig implements InitializingBean {
	private static final Logger logger = Logger.getLogger(InitSystemConfig.class);
	@Autowired
	private ApplicationContext ctx;

	@Override
	public void afterPropertiesSet() throws Exception {
		logger.info("start init user config ...");
		try {
			logger.info("reset job time expression ...");
			resetJobTimeExpression();
		} catch (Throwable e) {
			logger.error("", e);
		}
	}

	private void resetJobTimeExpression() {
		JobTimeExpression expression = new JobTimeExpression();
		// 测试手动输入
		// 设置定时任务ID
		expression.setJob("timeExpressionResetJob");
		// 设置运行serverIP
		expression.setServerIp("");
		// 对应触发器ID
		expression.setTrigger("timeExpressionResetJobTrigger");
		// 设置时间规则
		// expression.setExpression("0 0/1 * * * ?");// 每分钟0秒执行
		try {
			// 获得JOB对象
			BaseJob job = ctx.getBean(expression.getJob(), BaseJob.class);
			// 设置job运行server
			job.setServerIp(expression.getServerIp());
			// 获得定时任务触发器对象
			CronTriggerBean trigger = ctx.getBean(expression.getTrigger(), CronTriggerBean.class);
			// 触发器时间规则判断（未考虑规则正确性）
			if (trigger != null && StringUtils.isNotEmpty(expression.getExpression()) && !trigger.getCronExpression().equalsIgnoreCase(expression.getExpression())) {
				logger.info("reset job time expression" + JSON.toJSONString(expression));
				// 设置新规则
				trigger.setCronExpression(expression.getExpression());
			}
		} catch (Throwable t) {
			logger.error("", t);
		}
	}
}
